<template>
  <div>
    <template v-if="addFaultAuth && !isReceipt">
      <el-button type="primary" icon="el-icon-plus" plain size="mini" @click="openChooseFaultDialog">{{ $t('common.faultLibrary.addFromFaultLibrary') }}</el-button>
      <el-button type="primary" icon="el-icon-plus" plain size="mini" @click="openComposite">{{ $t('common.base.create') }}</el-button>
    </template>
    <template v-if="addFaultAuth && isReceipt">
      <span @click="openChooseFaultDialog" class="fault-library-text">{{ $t('common.faultLibrary.addFromFaultLibrary') }}</span>
    </template>

    <el-table v-table-style v-loading="listLoading" :style="tableBorderBottomStyle" header-row-class-name="base-table-header-v3" row-class-name="base-table-row-v3" :data="tableAllData"
      max-height="500">
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column v-for="(column, index) in faultTableColumns" :key="`${column.fieldName}_${index}`"
        :label="column.displayName" :prop="column.fieldName" :width="column.width"
        :fixed='column.isFixed'>
        <template slot-scope="scope">

          <!-- start 故障节点 -->
          <template v-if="column.fieldName === 'faultDesc'">
            <template v-if="scope.row[column.fieldName]">
              <span class="table-faultDesc-text">{{ scope.row[column.fieldName] }}</span>
            </template>
          </template>
          <!-- end 故障节点 -->

          <!-- start 解决方法 -->
          <template v-if="column.fieldName === 'solutionDesc'">
            <template v-if="scope.row.solutionId">
              <span class="resolve-view" @click="handelResolvent(scope.row)">{{ $t('common.base.view') }}</span>
            </template>
          </template>
          <!-- end 解决方法 -->
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100" v-if="editFaultBtn ||deleteFaultBtn">
        <template slot-scope="{ row, $index }">
          <span class="resolve-view btns-edit" v-if="!isReceipt && ((isTaskAdd && !row.isTree) || (!isTaskAdd && !row.isTree && row.faultEdit && editFaultBtn))" type="text" @click="openComposite(row, $index)">{{ $t('common.base.edit') }}</span>
          <span class="resolve-view" v-if="deleteFaultBtn" type="text" @click="handelDelete(row, $index)">{{ $t('common.base.delete') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部数据量统计 -->
     <div class="table-footer">
      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{tableAllData.length || 0}}</span>
      </i18n>
    </div>

    <!-- 查看弹窗 -->
    <choose-fault-detail-dialog ref="faultDetailDialog"></choose-fault-detail-dialog>
    <!-- 选择故障清单弹窗 -->
    <choose-fault-dialog :default-checked-keys="checkedKeys" :task="task" form="fault-table" ref="chooseFaultDialog" @submit="addChooseFault" />
    <!-- 新建故障和解决方案结合的弹框 -->
    <FaultCompositeDialog 
      v-if="!isReceipt" 
      v-model="faultCompositeDialogVisible" 
      :create-fault-data="createFaultData" 
      :faultSource="1" 
      :task="task" 
      @success="addTableData" />

  </div>
</template>
  
<script>
/* api */
import { taskFaultCardDelete, getTaskFaultCardSelect, getTaskCardSaveList, solutionDelete, libraryDelete } from '@src/api/Fault';
// components
import ChooseFaultDetailDialog from '@src/modules/faultLibrary/components/ChooseFaultDetailDialog.vue';
import ChooseFaultDialog from '@src/modules/task/editAllot/components/PartSeviceList/components/ChooseFaultDialog.vue';
import FaultCompositeDialog from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultCompositeDialog.vue';
// 故障描述弹框
import FaultDescription from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultDescription';
// 解决方案弹框
import FaultSolution from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultSolution';
import { findParents } from '@src/modules/faultLibrary/utils/index';
/* model */
import MsgModel from '@model/MsgModel';
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
// util
import AuthUtil from '@src/util/auth';
import { message } from '@src/util/message';
import { isArray } from '@src/util/type'

export default {
  name: 'fault-table',
  inject: ['initData'],
  components: {
    [ChooseFaultDetailDialog.name]: ChooseFaultDetailDialog,
    [ChooseFaultDialog.name]: ChooseFaultDialog,
    FaultDescription,
    // 新建/编辑解决方案
    FaultSolution,
    FaultCompositeDialog,
  },
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    // 工单数据
    task: {
      type: Object,
      default: () => ({})
    },
    // 是否工单回执进来
    isReceipt: {
      type: Boolean,
      default: false
    },
    // 因为新建详情页面的权限来源不一致，而且后端返回的也不是一个名字固传进来
    // 新建权限
    addFaultAuth: {
      type: Boolean,
      default: false
    },
    deleteFaultBtn: {
      type: Boolean,
      default: false
    },
    editFaultBtn: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      listLoading: false,
      // 新建/编辑故障对象弹框
      faultObjDialogVisible: false,
      // 当前编辑的故障对象id
      currentFaultObjId: '',
      // 新建/编辑故障描述弹框
      faultDescriptionDialogVisible: false,
      // 当前编辑的故障描述id
      currentFaultDescriptionId: '',
      // 新建/编辑解决方案弹框
      faultSolutionDialogVisible: false,
      // 当前编辑的解决方案id
      currentFaultSolutionId: '',
      // 用于记录新建故障描述和解决方案时一些数据，从列表取得，传给弹框
      createFaultData: {},
      // 所有表格数据（包含空内容
      tableAllData: [],
      // 空数据设置
      tableEmpty: false,
      checkedKeys: [],
      faultCompositeDialogVisible: false,
      currentFaultCompositeId: ''
    }
  },
  computed: {
    faultTableColumns() {
      return [
        {
          fieldName: 'faultDesc',
          displayName: i18n.t('common.base.description1'),
          formType: 'text',
          setting: {},
          isSystem: 1,
          isSearch: 0,
        },
        {
          fieldName: 'solutionDesc',
          displayName: i18n.t('faultLibrary.solution'),
          formType: 'text',
          width: '120px',
          setting: {},
          isSystem: 1,
          isSearch: 0,
        },
      ]
    },
    auth() {
      return this.initData?.auth || {};
    },
    isTaskAdd() {
      return !(this.task.id || '');
    },
    // 是否详情页面展示
    isView() {
      return this.task.id && !this.isReceipt;
    },
    // 表格样式
    tableBorderBottomStyle() {
      return {
        'border-bottom': this.tableAllData?.length ? 'none' : '1px solid #e8e8e8'
      }
    },
  },
  watch:{ 
    data(newV,oldV) {
      if(!this.task.id || this.isReceipt) this.tableAllData = newV || [];
    }
  },
  mounted() {
    const newFaultLibrary = this.initData?.receiptExpenseSheetForUpdate?.baseTaskFaultLibrary || [];
    // 工单详情、完成回执获取内容。回执时从init获取暂存中的内容。没有再请求select接口
    if(this.isView || (this.isReceipt && isArray(newFaultLibrary) && !newFaultLibrary.length)) {
      this.getTaskFaultTableData();
    }
    if(this.isReceipt && isArray(newFaultLibrary) && newFaultLibrary.length) {
      this.tableAllData = newFaultLibrary;
      this.emitToReceipt();
    }
  },
  methods: {
    openFaultDialogAuto() {
      if(this.addFaultAuth && !this.isReceipt) {
        this.openComposite()
      }
    },

    async getTaskFaultTableData(){
      try {
        this.listLoading = true;
        const res = await getTaskFaultCardSelect({
          taskId: this.task.id
        });
        
        if(!MsgModel.isSuccess(res)) return message.error(res.message);

        const checkedKeys = [];

        // 展示数据处理
        this.tableAllData = (res.data || []).map(x => {
          const { solutionVO, objDesc, taskId, taskNo , solutionId, faultSource, id, faultDesc, faultId, faultEdit, solutionEdit } = x || {};

          if(solutionVO){
            checkedKeys.push(solutionVO.id);
          }else if(!solutionVO) {
            checkedKeys.push(faultId);
          }

          return {
            id,
            solutionDesc: solutionVO?.solutionDesc || '',
            taskId,
            taskNo,
            solutionId,
            faultId,
            parentId: solutionVO?.libraryId || '',
            faultDesc,
            isTree: solutionVO?.solutionSource === 0 || faultSource === 0,
            objDesc,
            faultEdit,
            solutionEdit,
          }
        })
        this.checkedKeys = checkedKeys;

        if(this.isReceipt) this.emitToReceipt();
      }catch(e) {
        console.log('getTaskFaultCardSelect: ', e)
      } finally {
        this.listLoading = false;
      }
    },
    handelResolvent(row) {
      this.$refs.faultDetailDialog.open(row.solutionId);
    },
    handelDelete(row, index) {
      // 去除空数据
      if(row.faultEmpty && row.solutionEmpty) {
        this.tableEmpty = false;
        this.tableAllData.splice(index, 1);
        return;
      }
      
      // 故障树创建 不请求接口 直接删除
      if((row.isTree && !row.id) || row.faultEmpty || this.isReceipt) {
        this.tableAllData.splice(index, 1);

        if(this.isReceipt) this.emitToReceipt();
      }else {
        this.deleteRow(row, index);
      }
    },
    /** 打开添加故障清单弹窗 */
    openChooseFaultDialog() {
      this.$refs.chooseFaultDialog.open();
    },
    // 打开描述和子描述弹框
    openDescription(row = {}) {
      this.faultDescriptionDialogVisible = true;
      this.currentFaultDescriptionId = row.faultId || '';
      this.createFaultData = {
        objDesc: row.objDesc,
        id: row.id
      }
    },
    // 打开添加弹窗
    openComposite(row = {}) {
      this.createFaultData = {
        id: row.id,
        objDesc: row.objDesc,
        isShowSuperior: true, // 是否显示上级故障描述
        parentId: row.faultId, 
        parentDesc: row.faultDesc,
        solutionId: row.solutionId,
      }
      this.faultCompositeDialogVisible = true;
    },
    // 打开解决方案弹框
    openSolution(row = {}) {

      // if(!row.solutionId) {
        this.createFaultData = {
          id: row.id,
          parentId: row.faultId, 
          parentDesc: row.faultDesc,
          objDesc: row.objDesc,
        }
      // }
      
      this.faultSolutionDialogVisible = true;
      this.currentFaultSolutionId = row.solutionId || '';

    },
    // 添加完的回调
    addTableData(data) {
      if(this.isView) return this.timeoutGetData();
      const { faultDesc, id, solutionId, parentDesc, solutionDesc, isEdit } = data;
      const item = {
        faultDesc: `${parentDesc}/${faultDesc}/${solutionDesc}`,
        faultId: id,
        id,
        solutionId,
        solutionEmpty: false,
      }
      // 新建追加
      if (!isEdit) {
        this.tableAllData.push(item);
      } else {
        let index = this.tableAllData.findIndex(table => table.solutionId == item.solutionId)
        // 编辑表单 - 覆盖
        this.$set(this.tableAllData, index, item);
      }
      this.emitToReceipt();
    },
    /** 添加故障清单 */
    async addChooseFault(data, faultList) {
      const { id, taskNo } = this.task || {};
      const params = data.filter(x => !x.disabled).map(x => {
        const parents = findParents(faultList, x.id);
        const isSolution = x.dataType === 2;
        const solutionDesc = isSolution ? parents.splice(parents.length, 1) : '';

        const info = {
          taskId: id,
          taskNo: taskNo,
          solutionId: '',
          faultId: '',
          parentId: x.parentId || '',
          faultDesc: (parents?.map(x => x.faultDesc) || []).join('/'),
          solutionDesc,
          isTree: true,
          faultLevel: x.faultLevel,
          notChildren: !x.childrenList?.length
        }

        if(x.dataType === 1) {
          info.faultId = x.id;
        }else {
          info.solutionId = x.id;
          if(x.libraryId) info.faultId = x.libraryId;
        }

        return info;
      })
      
      if(this.isView) {
        const params1 = this.buildParams(params, faultList);
        await this.taskBindFaultList(params1);
      }

      this.$emit('dataChange', this.data.concat(params));
      this.$refs.chooseFaultDialog.close()
    },
    // 故障库绑定工单-多个
    async taskBindFaultList(params) {
      try {
        const res = await getTaskCardSaveList(params);

        if(res.success){
          // 更新页面数据
          if(this.isView) {
            this.timeoutGetData();
          }
        }
      }catch(e) {
        console.log('getTaskCardSaveList: ', e)
      }
    },
    buildParams(list = [], faultList = []) {
      // 处理数据
      const params = list.map(x => {
        return {
          taskId: this.task.id,
          taskNo: this.task.taskNo,
          faultId: x.faultId,
          faultLevel: x.faultLevel,
          solutionId: x.solutionId,
          faultDesc: x.faultDesc
        }
      })

      return params;
    },
    // 删除操作
    async deleteRow(row, index) {
      this.$confirm(this.$t('common.base.tip.confirmDeleteTip'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          // 新建工单删除
          if(!this.isView && !this.task.id) {
            this.deleteHandle(row, index);
            return;
          }

          // 以下是详情删除
          const res = await taskFaultCardDelete({ id: row.id, permissionsHide: true });
          if(!MsgModel.isSuccess(res)) return message.error(res.message);
          // 详情请求数据
          if(this.isView) return this.timeoutGetData();

          this.tableAllData.splice(index, 1);
          this.emitToReceipt();
        })
        .catch(err => {
          console.error(err)
        });
    },
    timeoutGetData() {
      setTimeout(() => {
        this.getTaskFaultTableData();
      }, 200);
    },
    // 传递数据
    emitToReceipt() {
      this.$emit('dataChange', this.tableAllData);
    },
    // 删除新建的故障节点或解决方法
    async deleteHandle(row, index){
      const { faultId, solutionId } = row;
      let res = {}

      if(solutionId) {
        res = await solutionDelete({ solutionId, permissionsHide: true })
        if(res.status === 0){
          res = await libraryDelete({ faultId, permissionsHide: true });
        }
      }else {
        res = await libraryDelete({ faultId, permissionsHide: true });
      }

      if(res.status === 0){
        this.tableAllData.splice(index, 1);
        this.emitToReceipt();
      }
    },
  },
}
</script>
  
<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}

.el-table {
  border: 1px solid #e8e8e8;

  .resolve-view {
    color: $color-primary;
    cursor: pointer;
  }
  .table-add-text {
    color: #BFBFBF;
    font-size: 14px;
    cursor: pointer;
  }

  .table-faultDesc-text {
    width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  
  .el-button {
    margin-bottom: 0;
  }
}

.el-button {
  border-radius: $button-radius-base;
  margin-bottom: 10px;
}

.el-icon-edit-outline {
  margin-left: 20px;
  cursor: pointer;
}

.fault-library-text {
  color: $color-primary;
  cursor: pointer;
}

.btns-edit {
  margin-right: 12px;
}
</style>